const { JJMessageHelp, JJMessageBoard, JJBanks, JJUserBank } = require('../../models/ctcdb');
const BaseResp = require('../../utils/baseResp');
const errorCode = require('../../utils/errorCode');

async function getBaseDesign() {
  const detail = await JJMessageHelp.findOne({
    where: {},
    raw: true,
    attributes: ['wechat', 'phone', 'userProtocel']
  });
  return detail
}

async function writeMessage({ message, userId }) {
  await JJMessageBoard.create({
    message,
    userId
  })
}

async function getBankList() {
  const list = await JJBanks.findAll({
    where: {
      status: 1
    },
    attributes: ['id', 'bankName'],
    raw: true
  });
  return {
    list
  }
}

async function addBankInfo({ bankId, bankNo, realName, userId }) {
  const bankInfo = await JJBanks.findOne({
    where: {
      id: bankId,
      status: 1
    },
    attributes: ['id'],
    raw: true
  });
  if (!bankInfo) {
    throw BaseResp.error(errorCode.OTHER.NOT_BANK)
  }
  const userBankInfo = await JJUserBank.findOne({
    where: {
      userId
    },
    attributes: ['id'],
    raw: true
  });
  if (!userBankInfo) {
    await JJUserBank.create({
      bankId,
      bankNo,
      realName,
      userId
    })
  } else {
    const { id } = userBankInfo;
    await JJUserBank.update({
      bankId,
      bankNo,
      realName
    }, {
      where: {
        id
      }
    })
  }
}

async function getBankInfo({ userId }) {
  const userBank = await JJUserBank.findOne({
    where: {
      userId
    },
    attributes: ['userId', 'id', 'bankNo', 'bankId', 'realName'],
    raw: true
  });
  if (!userBank) {
    return {}
  }
  const { bankId } = userBank;
  const bankInfo = await JJBanks.findOne({
    where: {
      id: bankId
    },
    attributes: ['bankName'],
    raw: true
  });
  userBank.bankName = bankInfo && bankInfo.bankName || '';
  return userBank;
}

module.exports = {
  getBaseDesign,
  writeMessage,
  getBankList,
  addBankInfo,
  getBankInfo
};
